package com.admin.listener;

import com.admin.annotations.EnableEureka;
import com.admin.annotations.EnableNacos;
import com.admin.config.EurekaConfigProcessor;
import com.admin.config.NacosConfigProcessor;
import com.admin.model.ServiceRegistryState;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

@Component
public class EurekaApplicationListener implements ApplicationListener<ApplicationReadyEvent> {

    private ApplicationContext context;

    public EurekaApplicationListener(ApplicationContext context) {
        this.context = context;
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        // 获取主应用类
        Class<?> mainClass = event.getSpringApplication().getMainApplicationClass();

        // 检查主应用类是否有 @EnableNacos 注解
        if (AnnotationUtils.findAnnotation(mainClass, EnableEureka.class) != null) {
            handleEnableEureka();
            ServiceRegistryState.setEurekaEnabled(true);
        }
    }

    private void handleEnableEureka() {
        // 从 Spring 上下文获取 EurekaConfigProcessor Bean
        EurekaConfigProcessor eurekaProcessor = context.getBean(EurekaConfigProcessor.class);
        // 调用 process 方法以注册服务
        eurekaProcessor.process();
    }
}
